package libs.yzx.zaza.acts;

import android.os.Handler;
import android.os.Looper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkUpFile {

    private final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(4000, TimeUnit.MILLISECONDS)
            .writeTimeout(4000,TimeUnit.MILLISECONDS).readTimeout(4000,TimeUnit.MILLISECONDS).build();
    private final Handler handler = new Handler(Looper.getMainLooper());

    private Call currentCall;


    public void cancel(){
        if(currentCall != null) {
            currentCall.cancel();
            currentCall = null;
        }
    }

    public void uploadFile(String url , List<File>fList , HashMap<String,String> params , final OnFileUploadCompleteListener onFileUploadCompleteListener){
        cancel();
        if( fList == null) fList =new ArrayList<>(0);
        if(params == null) params = new HashMap<>(0);

        MultipartBody.Builder builder = new MultipartBody.Builder("xx--------------------------------------------xx").setType(MultipartBody.FORM);

        for (Map.Entry<String, String> entry : params.entrySet())
            builder.addFormDataPart(entry.getKey(),entry.getValue());
        for (File file : fList)
            builder.addFormDataPart("files",file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file));

        currentCall = client.newCall(new Request.Builder().url(url).post(builder.build()).build());
        currentCall.enqueue(new Callback() {
            public void onResponse(Call call, Response response) throws IOException {
                final int code = response.code();
                final String data = response.body().string();
                final boolean isSuccess = response.isSuccessful();
                handler.post(new Runnable() {
                    public void run() {
                        if(isSuccess)
                            onFileUploadCompleteListener.onSuccess(data);
                        else
                            onFileUploadCompleteListener.onError(code);
                    }
                });
            }
            public void onFailure(Call call, IOException e) {
                handler.post(new Runnable() {
                    public void run() {
                        onFileUploadCompleteListener.onError(0);
                    }
                });
            }
        });
    }


    /*  */
    /*  */
    /*  */


    public interface OnFileUploadCompleteListener{
        void onSuccess(String data);
        void onError(int httpCode);
    }

}

